#include <iostream>
using namespace std;

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
static int writeFile(const char * filename,const void *buf,size_t size)
{
    int fd = open(filename,O_RDWR | O_CREAT,0644);
    if(fd == 0)
    {
        perror("open error");
        return -1;
    }

    int writeBytes = write(fd,buf,size);
    close(fd);
    return writeBytes;
}

static int readFile(const char * filename, void *buf,size_t size)
{
    int fd = open(filename,O_RDWR | O_CREAT,0644);
    if(fd == 0)
    {
        perror("open error");
        return -1;
    }

    int readBytes = read(fd,buf,size);
    close(fd);
    return readBytes;
}
int main()
{   
    int num =100;
    //创建子进程
    //子进程和父进程的执行顺序没有必然联系
    //fork和vfork的唯一区别是vfork先让子进程先执行
    pid_t pid = fork();
    if(pid > 0)
    {   
        num+=666;
        writeFile("./test.txt",&num,sizeof(num));
        printf("parent process -num:%d\n",num);
        //父进程的程序
        printf("parent process - child pid = %d\n",pid);
    }
    else if(pid ==  0)
    {
        sleep(3);
        const char * filename = "./test.txt";
       
        int buffer = 0;
        readFile("./test.txt",&buffer,sizeof(buffer));

        printf("child process - num:%d\n",buffer);
        //子进程的代码
        printf("child process -pid = %d,ppid = %d\n",getpid(),getppid());
        exit(-1);
    }
    else if(pid < 0)
    {
        perror("fork error:");
        exit(-1);
    }
    printf("hello,world\n");
    //回收子进程的资源
    wait(NULL);
    return 0;
}